package com.agileai.miscdp.hotweb.ui.actions.standard;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.generator.standard.SMHandlerCfgGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMHandlerGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMJspPagGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMServiceCfgGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMServiceClassGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMServiceInterfaceGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMSqlMapCfgGenerator;
import com.agileai.miscdp.hotweb.generator.standard.SMSqlMapGenerator;
import com.agileai.miscdp.hotweb.ui.actions.BaseGenCodesAction;
import com.agileai.miscdp.hotweb.ui.dialogs.CodeGenConfigDialog;
import com.agileai.miscdp.hotweb.ui.editors.standard.StandardModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.standard.StandardModelEditorContributor;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.domain.KeyNamePair;
import com.agileai.util.FileUtil;
/**
 * 代码生成动作
 */
public class SMGenCodesAction extends BaseGenCodesAction{
	private static final String GenOptionSection = "StandardModelEditor.GeneratorOption";
	
	public SMGenCodesAction() {
	}
	public void setContributor(StandardModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	public void run() {
		StandardModelEditor modelEditor = (StandardModelEditor)this.getModelEditor();
		Shell shell = modelEditor.getSite().getShell();
    	if (modelEditor.isDirty()){
    		String confirmTitle = MiscdpUtil.getIniReader().getValue("DialogInfomation","ConfirmTitle");
    		String confirmMsg = MiscdpUtil.getIniReader().getValue("DialogInfomation","IsSaveFirst");
    		boolean saveFirst = MessageDialog.openConfirm(shell, confirmTitle, confirmMsg);
    		if (saveFirst){
    			modelEditor.doSave(new NullProgressMonitor());
    		}else{
    			return;
    		}
    	}
    	funcModel = modelEditor.buildFuncModel();		
		CodeGenConfigDialog configDialog = new CodeGenConfigDialog(shell);
		List<KeyNamePair> inputGenList = new ArrayList<KeyNamePair>();
		inputGenList = MiscdpUtil.getIniReader().getList(GenOptionSection);
		configDialog.setInputGenList(inputGenList);
		configDialog.open();
		if (configDialog.getReturnCode() != Dialog.OK){
			return;
		}
		genertorMap = configDialog.getSelectedKeyNamePairs();
		
		IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
		try {
	    	String projectName = funcModel.getProjectName();
	    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
			progressService.runInUI(progressService,this,project);
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	public void run(IProgressMonitor monitor) throws InvocationTargetException,
			InterruptedException {
		monitor.beginTask("init model values:", 1000);
		monitor.subTask("set model values....");
		monitor.worked(50);
    	String projectName = funcModel.getProjectName();
    	IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
		File xmlFile = getXmlFile();
		String tableName = ((StandardFuncModel)funcModel).getTableName();
		String srcDir = project.getLocation().toString()+"/src";
//		this.funcModel = funcModel.buildFuncModel(xmlFile);
		
		if (genertorMap.containsKey(GEN_OPTION_JSPPAGE)){
			monitor.subTask("generating jsp files....");
			monitor.worked(200);
			SMJspPagGenerator sMJspPagGenerator = new SMJspPagGenerator();
			sMJspPagGenerator.setXmlFile(xmlFile);
			
	    	String listJspName = project.getLocation().toString()+"/WebRoot/jsp/"+((StandardFuncModel)funcModel).getListJspName();
	    	String detailJspName = project.getLocation().toString()+"/WebRoot/jsp/"+((StandardFuncModel)funcModel).getDetailJspName();
			sMJspPagGenerator.setListJspFile(listJspName);
			sMJspPagGenerator.setDetailJspFile(detailJspName);
			sMJspPagGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMJspPagGenerator.generate();
		}
		if (genertorMap.containsKey(GEN_OPTION_SQLMAP_DEFINE)){
			monitor.subTask("generating SqlMap files....");
			monitor.worked(300);
			SMSqlMapGenerator sMSqlMapGenerator = new SMSqlMapGenerator(projectName);
			String[] colNames = MiscdpUtil.getColNames(((StandardFuncModel)funcModel).getPageFormFields());
			String findRecordsSql = funcModel.getListSql();
			
			sMSqlMapGenerator.setFuncModel((StandardFuncModel)funcModel);			
			sMSqlMapGenerator.setColNames(colNames);
			sMSqlMapGenerator.setFindRecordsSql(findRecordsSql);
			sMSqlMapGenerator.setTableName(tableName);
	    	String abstSqlMapPath = project.getLocation().toString()+"/src/sqlmap";
	    	File tempFile = new File(abstSqlMapPath);
	    	if (!tempFile.exists()){
	    		tempFile.mkdirs();
	    	}
	    	String sqlMapFileName = MiscdpUtil.getValidName(tableName); 
	    	String sqlMapFile = abstSqlMapPath + "/" + sqlMapFileName+".xml";
	    	sMSqlMapGenerator.setSqlMapFile(sqlMapFile);
			sMSqlMapGenerator.generate();
		}
		
		if (genertorMap.containsKey(GEN_OPTION_SQLMAP_INDEX)){
			monitor.subTask("generating SqlMap config files....");
			monitor.worked(400);
			SMSqlMapCfgGenerator sMSqlMapCfgGenerator = new SMSqlMapCfgGenerator();
			String abstSqlMapCfgPath = project.getLocation().toString()+"/src/SqlMapConfig.xml";
			sMSqlMapCfgGenerator.setTableName(tableName);
			sMSqlMapCfgGenerator.setConfigFile(abstSqlMapCfgPath);
			sMSqlMapCfgGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMSqlMapCfgGenerator.generate();
		}

		if (genertorMap.containsKey(GEN_OPTION_SERVICE_CONFIG)){
			monitor.subTask("generating Service config files....");
			monitor.worked(500);
			SMServiceCfgGenerator sMServiceCfgGenerator = new SMServiceCfgGenerator();
			String abstServiceCfgPath = project.getLocation().toString()+"/src/ServiceContext.xml";
			sMServiceCfgGenerator.setConfigFile(abstServiceCfgPath);
			sMServiceCfgGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMServiceCfgGenerator.generate();
		}
		
		if (genertorMap.containsKey(GEN_OPTION_HANDLER_CONFIG)){
			monitor.subTask("generating Handler config files....");
			monitor.worked(600);
			SMHandlerCfgGenerator sMHandlerCfgGenerator = new SMHandlerCfgGenerator();
			String abstHandlerCfgPath = project.getLocation().toString()+"/src/HandlerContext.xml";
			sMHandlerCfgGenerator.setConfigFile(abstHandlerCfgPath);
			sMHandlerCfgGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMHandlerCfgGenerator.generate();
			
		}
		if (genertorMap.containsKey(GEN_OPTION_HANDLER_CLASS)){
			monitor.subTask("generating Handler java files....");
			monitor.worked(700);
		
			SMHandlerGenerator sMHandlerGenerator = new SMHandlerGenerator();
			sMHandlerGenerator.setSrcPath(srcDir);
			StandardFuncModel standardFuncModel = (StandardFuncModel)funcModel;
			String listHandlerClassName = standardFuncModel.getListHandlerClass();
			sMHandlerGenerator.setListHandlerClassName(listHandlerClassName);
			String editHandlerClassName = standardFuncModel.getEditHandlerClass();
			sMHandlerGenerator.setEditHandlerClassName(editHandlerClassName);
			sMHandlerGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMHandlerGenerator.setXmlFile(xmlFile);
			sMHandlerGenerator.setAppName(projectName);
			sMHandlerGenerator.generate();
		}
		if (genertorMap.containsKey(GEN_OPTION_SERVICE_IMPL)){
			monitor.subTask("generating Service Impl java files....");
			monitor.worked(800);
			
			SMServiceClassGenerator sMServiceClassGenerator = new SMServiceClassGenerator();
			String implClassName = funcModel.getImplClassName();
			File implJavaFile = FileUtil.createJavaFile(srcDir, implClassName);
			String implJavaFilePath = implJavaFile.getAbsolutePath();
			sMServiceClassGenerator.setJavaFile(implJavaFilePath);
			sMServiceClassGenerator.setXmlFile(xmlFile);
			sMServiceClassGenerator.setFuncModel((StandardFuncModel)funcModel);
			sMServiceClassGenerator.generate();
			try {
				MiscdpUtil.getJavaFormater().format(implJavaFilePath, sMServiceClassGenerator.getCharencoding());	
			} catch (Exception e) {
				e.printStackTrace();
				throw new InvocationTargetException(e);
			}
		}
		if (genertorMap.containsKey(GEN_OPTION_SERVICE_INTERFACE)){
			monitor.subTask("generating Service Interface java files....");
			monitor.worked(900);
			SMServiceInterfaceGenerator sMServiceInterfaceGenerator = new SMServiceInterfaceGenerator();
			String interfaceClassName = funcModel.getInterfaceName();
			File interfaceJavaFile = FileUtil.createJavaFile(srcDir, interfaceClassName);
			String interfaceJavaFilePath = interfaceJavaFile.getAbsolutePath();
			sMServiceInterfaceGenerator.setJavaFile(interfaceJavaFilePath);
			sMServiceInterfaceGenerator.setXmlFile(xmlFile);
			sMServiceInterfaceGenerator.generate();
			try {
				MiscdpUtil.getJavaFormater().format(interfaceJavaFilePath, sMServiceInterfaceGenerator.getCharencoding());
			} catch (IOException e1) {
				e1.printStackTrace();
				throw new InvocationTargetException(e1);
			}
		}
			
		try {
			project.refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}
}
